<template>
  <!-- 编辑个人信息 -->
  <div class="EditInformation">
    <CommonHeader title="编辑个人信息">
      <template #left>
        <div class="back-icon">
          <Icon name="zuojiantou" />
          <span>返回</span>
        </div>
      </template>
    </CommonHeader>
    <!-- 编辑个人信息表单 -->
    <div class="form">
      <div class="form_item">
        <div class="label">用户昵称</div>
        <div class="input">
          <input
            v-model="formData.nickname"
            type="text"
            placeholder="请输入用户昵称"
          />
        </div>
      </div>
      <!-- 会员头像 -->
      <div class="form_item">
        <div class="label">会员头像</div>
        <div class="input">
          <!-- 修改头像展示逻辑 -->
          <div class="avatar" v-for="item in avatarList" :key="item.id">
            <img :src="item.url" alt="" />
            <div class="close" @click.stop="removeAvatar(item)">
              <Icon name="close" color="#fff" size="8px" />
            </div>
          </div>
          <div class="upload" @click="handleUpload">
            <Icon name="zhaoxiangji" color="#ccc" size="30px" />
          </div>
          <!-- 隐藏的文件上传输入框 -->
          <input
            type="file"
            ref="upload"
            style="display: none"
            @change="onFileChange"
            accept="image/*"
          />
        </div>
      </div>
      <!-- 单选框 -->
      <div class="form_item">
        <div class="label">单选框</div>
        <div class="input">
          <div class="radio_group">
            <div class="radio_item">
              <div
                class="cart_footer_check"
                :class="{ active: formData.sex === 1 }"
              ></div>
              <label @click="selectSex(1)">男</label>
            </div>
            <div class="radio_item">
              <div
                class="cart_footer_check"
                :class="{ active: formData.sex === 2 }"
              ></div>
              <label @click="selectSex(2)">女</label>
            </div>
          </div>
        </div>
      </div>
      <!-- 日历 -->
      <div class="form_item" @click="calendarShow = true">
        <div class="label">日历</div>
        <div class="input">
          <input
            type="text"
            placeholder="请选择日期"
            readonly
            v-model="formData.birthday"
          />
        </div>
      </div>
      <!-- 地区选择 -->
      <div class="form_item" @click="popupShow = true">
        <div class="label">地区选择</div>
        <div class="input">
          <input
            type="text"
            readonly
            v-model="formData.region"
            placeholder="请选择地区"
          />
        </div>
      </div>
    </div>
    <!-- 提交按钮 -->
    <div class="submit_btn" @click="handleSubmit">
      <button class="btn">提交</button>
    </div>
    <Popup
      :isShow="popupShow"
      @update:isShow="popupShow = $event"
      @confirm="onConfirm"
    >
    </Popup>
    <Calendar
      :visible="calendarShow"
      @update:visible="calendarShow = $event"
      @confirm="handleConfirm"
    ></Calendar>
  </div>
</template>

<script>
import CommonHeader from '@/components/common/publicHeader/index.vue';

// 导入地区选择组件
import Popup from '@/components/common/popup/index.vue';
import { editUserInfoAPI, editUserInfoUpdateAPI } from '@/api/my';
import Calendar from '@/components/common/calendar/index.vue';
import Message from '@/utils/message';

export default {
  name: 'EditInformation',
  components: {
    CommonHeader,
    Popup,
    Calendar,
  },
  data() {
    return {
      popupShow: false,
      areaInput: '',
      avatarList: [], // 所有要展示的图片（包含服务器图 + 本地预览图）
      formData: {
        avatarurl: '', // 用于提交的头像字段，只存路径（如：uploads/xxx.jpg）
      },
      // 控制弹窗
      calendarShow: false,
    };
  },
  async mounted() {
    await this.getUserInfo();
  },
  methods: {
    onConfirm(val) {
      const { province, city, area } = val;
      // 将所有存在的地区 label 收集起来
      const labels = [province, city, area]
        .filter(item => item) // 过滤 undefined/null
        .map(item => item.label); // 提取 label
      // 用逗号拼接
      this.formData.region = labels.join(',');
    },
    // 获取用户信息
    async getUserInfo() {
      const userinfo = JSON.parse(localStorage.getItem('userinfo'));
      let { list } = await editUserInfoAPI({
        uid: userinfo.uid,
      });
      let { nickname, avatarurl, sex, birthday, region, id } = list[0];
      // 处理一下 birthday 和 region 为 'null'
      if (birthday === 'null') {
        birthday = '';
      }
      if (region === 'null') {
        region = '';
      }
      this.formData = { nickname, avatarurl, sex, birthday, region, id };
      this.avatarList = [
        {
          id: 1,
          url: 'http://43.138.15.137:4000/' + avatarurl,
          type: 'server', // 标记来源
        },
      ];
    },
    async handleSubmit() {
      const data = {
        ...this.formData,
        avatarurl: this.avatarList[0].file
          ? this.avatarList[0].file
          : this.avatarList[0].url,
      };
      const formdata = new FormData();
      for (let key in data) {
        formdata.append(key, data[key]);
      }
      //  打印提交的表单数据
      let res = await editUserInfoUpdateAPI(formdata);
      const {
        code,
        list: { avatarurl },
        msg,
      } = res;
      if (code === 200) {
        Message.success(msg);
        // 更新本地存储头像
        const userinfo = JSON.parse(localStorage.getItem('userinfo'));
        userinfo.avatarurl = avatarurl;
        userinfo.nickname = data.nickname;
        localStorage.setItem('userinfo', JSON.stringify(userinfo));
        console.log(userinfo);
        // 跳转my页
        this.$router.push({
          name: 'my',
        });
      } else {
        Message.error(msg);
        return;
      }
    },
    handleUpload() {
      // 调起上传图片的方法
      this.$refs.upload.click();
    },
    onFileChange(event) {
      const files = event.target.files;
      if (files && files.length > 0) {
        for (let i = 0; i < files.length; i++) {
          const file = files[i];

          // 只处理图片
          if (!file.type.startsWith('image/')) continue;

          const previewUrl = URL.createObjectURL(file);

          // ✅ 添加到 avatarList，id 递增
          this.avatarList.push({
            id: Date.now() + i, // 确保唯一
            url: previewUrl,
            file, // 保留原始文件对象，用于后续上传
            type: 'local', // 标记为本地临时图
          });
        }

        // 重置 input
        event.target.value = '';
      }
    },
    // 删除图片
    removeAvatar(item) {
      this.avatarList = this.avatarList.filter(avatar => avatar.id !== item.id);
    },
    // 选择性别
    selectSex(sex) {
      this.formData.sex = sex;
    },
    handleConfirm(dateStr) {
      this.calendarShow = false;
      this.formData.birthday = dateStr;
    },
  },
};
</script>

<style lang="scss" scoped>
.form {
  padding: 10px;
  background-color: #fff;

  .form_item {
    padding: 10px 0;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    gap: 20px;

    .label {
      font-size: 12px;
      font-weight: 600;
      color: #333;
      line-height: 20px;
    }

    .input {
      flex: 1;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      input {
        width: 100%;
        height: 100%;
      }

      .avatar,
      .upload {
        width: 80px;
        height: 80px;
        border-radius: 5px;
        margin-right: 8px;
        margin-bottom: 8px;
        overflow: hidden;
        position: relative;

        img {
          width: 100%;
          height: 100%;
          border-radius: 5px;
          object-fit: cover;
        }

        .close {
          position: absolute;
          top: -5px;
          right: -5px;
          width: 20px;
          height: 20px;
          background-color: #000;
          color: #fff;
          font-size: 14px;
          font-weight: 600;
          line-height: 20px;
          text-align: left;
          border-radius: 25%;
          padding: 0 3px;
        }
      }

      .upload {
        background-color: #f7f8fa;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }

    .radio_group {
      display: flex;
      gap: 20px;

      .radio_item {
        display: flex;
        align-items: center;

        label {
          font-size: 14px;
          font-weight: 600;
          color: #333;
          line-height: 20px;
        }

        .cart_footer_check {
          width: 18px;
          height: 18px;
          border: 1px solid #ccc;
          border-radius: 50%;
          margin: 0 4px;
          position: relative;

          &.active {
            background-color: #0076ff;
            border: 0;

            &::before {
              content: '';
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -60%) rotate(45deg);
              width: 4px;
              height: 8px;
              border-right: 1px solid #fff;
              border-bottom: 1px solid #fff;
            }
          }
        }
      }
    }
  }
}

.submit_btn {
  padding: 10px;

  .btn {
    width: 100%;
    height: 40px;
    background-color: #ff6600;
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    line-height: 20px;
    border-radius: 20px;
    text-align: center;
  }
}
</style>
